package cn.edu.sdjzu.xg.bysj.controller.basic;
//201902104061徐中堂
import cn.edu.sdjzu.xg.bysj.domain.GraduateProject;
import cn.edu.sdjzu.xg.bysj.service.GraduateProjectService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
// 将所有方法组织在一个Controller(Servlet)中，应用过滤器
@Slf4j
@WebServlet("/basic/graduateProject.ctl")
public class GraduateProjectController extends HttpServlet {
    /**
     * GET, http://localhost:8080/basic/graduateProject.ctl, 查询毕设
     * 查询毕设对象：将来自前端请求的JSON对象
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            respMessage_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(respMessage_jsonObj);
            log.error("未收到信息");
            return;
        }
        //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":1}
        Object id_obj = req_jsonObj.get("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个毕设对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseGraduateProject(id_int, response);
                log.trace("查找id" + id_int);
            } else {//请求中包含条件和分页信息，需要响应多个毕设项目对象
                //读取分页信息，形成分页对象
                //从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
                Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
                //从请求JSONObject对象中读取键“condition”对应的值(描述查询条件的JSONArray对象)
                List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
                //响应多个教师信息，其中conditionList, pagination两个对象引用为空是可能的
                this.responseGraduateProjects(response, conditionList, pagination);
            }
        } catch (SQLException e){
            respMessage_jsonObj.put("message","数据库异常");
            log.error("数据库异常"+ e.getMessage());
        } catch(Exception e){
            respMessage_jsonObj.put("message","网络异常");
            log.error("网络异常" + e.getMessage());
        }
        finally {
            response.getWriter().println(respMessage_jsonObj);
        }
    }
    //响应一个毕业项目对象
    private void responseGraduateProject(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //根据id查找毕设项目
        GraduateProject graduateProject = GraduateProjectService.getInstance().find(id);
        //转化成json字串
        String graduateProject_json = JSON.toJSONString(graduateProject);
        //响应json到前端
        response.getWriter().println(graduateProject_json);
    }
    //响应所有对象
    private void responseGraduateProjects(HttpServletResponse response, Collection<Condition> condition, Pagination pagination)
            throws ServletException, IOException, SQLException {
        //获得所有
        Collection<GraduateProject> graduateProjects = GraduateProjectService.getInstance().findAll(condition,pagination);
        //将查到的对象集合序列化为JSON格式字串，第二个参数可以防止循环引用
        String degrees_json = JSON.toJSONString(graduateProjects, SerializerFeature.DisableCircularReferenceDetect);
        //创建json对象，向前端返回信息
        JSONObject message  = new JSONObject();
        message.put("totalNum",pagination.getTotalNum());
        message.put("data",degrees_json);
        response.getWriter().println(message);
    }
    /**
     * POST, http://localhost:8080/basic/graduateProject.ctl, 增加毕设
     * 增加一个毕设对象：将来自前端请求的JSON对象，增加到数据库表中
     * @param request 请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //获取前端传来的请求，转换为json子串
            String req_toAdd_jsonStr = JSONUtil.getJSON(request);
            log.trace(req_toAdd_jsonStr);
            //将JSON字串解析为要修改的graduateProject对象
            GraduateProject graduateProject = JSON.parseObject(req_toAdd_jsonStr,GraduateProject.class);
            log.trace(graduateProject.toString());
            //添加
            GraduateProjectService.getInstance().add(graduateProject);
            respMessage_jsonObj.put("message", "增加成功");
        } catch (SQLException e){
            respMessage_jsonObj.put("message","数据库异常");
            log.error(e.getMessage());
        } catch (Exception e){
            respMessage_jsonObj.put("message","网络异常");
            log.error(e.getMessage());
        } finally {
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
        }
    }
    /**
     * PUT, http://localhost:8080/basic/graduateProject.ctl, 修改毕设项目
     * 修改毕设对象：将来自前端请求的JSON对象
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException
     */
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            String toUpdate_jsonStr = JSONUtil.getJSON(request);
            //将JSON字串解析为要修改的graduateProject对象（有id的完整对象）
            GraduateProject graduateProject = JSON.parseObject(toUpdate_jsonStr, GraduateProject.class);
            //进行修改更新
            GraduateProjectService.getInstance().update(graduateProject);
            respMessage_jsonObj.put("message", "更新成功");
        } catch (SQLException e){
            respMessage_jsonObj.put("message","数据库异常");
            log.error(e.getMessage());
        } catch (Exception e){
            respMessage_jsonObj.put("message","网络异常");
            log.error(e.getMessage());
        } finally {
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
        }
    }
    /**
     * del, http://localhost:8080/basic/graduateProject.ctl, 删除毕设项目
     * @param request  请求对象
     * @param response 响应对象
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //将request参数转换为JSON字串
            String request_json_str = JSONUtil.getJSON(request);
            //将请求body解析为要删除的id对应的JSONObject对象(可能是{"id":1})
            JSONObject idOfToDelete_jsonObj = JSON.parseObject(request_json_str);
            //从JSONObject对象中读取键“id”的值（Java Object对象），
            Object id_obj = idOfToDelete_jsonObj.get("id");
            //转化为int类型数据
            int id_int = Integer.parseInt(id_obj.toString());
            GraduateProjectService.getInstance().delete(id_int);
            log.trace("删除id" + id_int);
            respMessage_jsonObj.put("message", "删除成功");
        } catch (SQLException e){
            respMessage_jsonObj.put("message","数据库异常");
            log.error(e.getMessage());
        } catch (Exception e){
            respMessage_jsonObj.put("message","网络异常");
            log.error(e.getMessage());
        } finally {
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
        }
    }
}
